﻿using System;
using System.Text;
using System.Web.UI;
using Microsoft.SharePoint;
using System.Xml;
using System.Xml.Xsl;
using System.ComponentModel;
using System.IO;
using System.Web;
using System.Xml.Serialization;
using System.Net;
using System.Xml.Linq;
using Microsoft.SharePoint.Utilities;
using Microsoft.SharePoint.WebPartPages;


namespace VPLink2013.Webparts
{
    public interface IXmlFileLinkedWebPart
    {
        string XmlFileURL
        {
            get;
            set;
        }
    }
    [ToolboxData("<{0}:ListViewWebPart runat=server></{0}:ListViewWebPart>"),
    XmlRoot(Namespace = "VPLink2013.Webparts")]
    abstract public class ListViewWebPart : WebPart
    {
        #region Properties

        protected Guid _webID = Guid.Empty;
        protected Guid _listID = Guid.Empty;
        protected string _filterField1;
        protected string _filterFieldType1;
        protected string _filterType1;
        protected string _filterValue1;
        protected string _filterField2;
        protected string _filterFieldType2;
        protected string _filterType2;
        protected string _filterValue2;
        protected string _filterOperator;
        protected bool _isLimited = false;
        protected uint _itemLimit;
        protected string _detailsPageUrl;
        protected string _newFormPageUrl;
        protected string _sortBy;
        protected bool _sortOrder;
        protected bool _itemLimitType;

        protected DateTime dtStart;

        abstract public int ListTemplate
        {
            get;
        }

        [Browsable(true), Category("Miscellaneous"),
        WebPartStorage(Storage.Shared),
        FriendlyName("WebID"),
        Description("Identifier of the web of the list of elements to display.")]
        public Guid WebID
        {
            get { return _webID; }
            set { _webID = value; }
        }

        [Browsable(true), Category("Miscellaneous"),
        DisplayName("ListID"),
        Description("Identifier of the list of elements to display.")]
        public Guid ListID
        {
            get { return _listID; }
            set { _listID = value; }
        }

        [Browsable(true), Category("Miscellaneous"),
        DisplayName("FilterField1"),
        Description("Field on which to filter."),
        DefaultValue("")]
        public string FilterField1
        {
            get { return _filterField1; }
            set { _filterField1 = value; }
        }

        [Browsable(true), Category("Miscellaneous"),
        WebPartStorage(Storage.Shared),
        FriendlyName("FilterFieldType1"),
        Description("Type of the filter field."),
        DefaultValue("")]
        public string FilterFieldType1
        {
            get { return _filterFieldType1; }
            set { _filterFieldType1 = value; }
        }

        [Browsable(true), Category("Miscellaneous"),
        WebPartStorage(Storage.Shared),
        FriendlyName("FilterValue1"),
        Description("Value of the filter."),
        DefaultValue("")]
        public string FilterValue1
        {
            get { return _filterValue1; }
            set { _filterValue1 = value; }
        }

        [Browsable(true), Category("Miscellaneous"),
        WebPartStorage(Storage.Shared),
        FriendlyName("FilterType1"),
        Description("Type of the filter."),
        DefaultValue("")]
        public string FilterType1
        {
            get { return _filterType1; }
            set { _filterType1 = value; }
        }

        [Browsable(true), Category("Miscellaneous"),
        WebPartStorage(Storage.Shared),
        FriendlyName("FilterField2"),
        Description("Field on which to filter."),
        DefaultValue("")]
        public string FilterField2
        {
            get { return _filterField2; }
            set { _filterField2 = value; }
        }

        [Browsable(true), Category("Miscellaneous"),
        WebPartStorage(Storage.Shared),
        FriendlyName("FilterFieldType2"),
        Description("Type of the filter field."),
        DefaultValue("")]
        public string FilterFieldType2
        {
            get { return _filterFieldType2; }
            set { _filterFieldType2 = value; }
        }

        [Browsable(true), Category("Miscellaneous"),
        WebPartStorage(Storage.Shared),
        FriendlyName("FilterValue2"),
        Description("Value of the filter."),
        DefaultValue("")]
        public string FilterValue2
        {
            get { return _filterValue2; }
            set { _filterValue2 = value; }
        }

        [Browsable(true), Category("Miscellaneous"),
        WebPartStorage(Storage.Shared),
        FriendlyName("FilterType2"),
        Description("Type of the filter."),
        DefaultValue("")]
        public string FilterType2
        {
            get { return _filterType2; }
            set { _filterType2 = value; }
        }

        [Browsable(true), Category("Miscellaneous"),
        WebPartStorage(Storage.Shared),
        FriendlyName("FilterOperator"),
        Description("Operator beteween two filters."),
        DefaultValue("")]
        public string FilterOperator
        {
            get { return _filterOperator; }
            set { _filterOperator = value; }
        }

        [Browsable(true), Category("Miscellaneous"),
        WebPartStorage(Storage.Shared),
        FriendlyName("IsLimited"),
        Description("Query of the WebPart : is the number of items limited."),
        DefaultValue(false)]
        public bool IsLimited
        {
            get { return _isLimited; }
            set { _isLimited = value; }
        }

        [Browsable(true), Category("Miscellaneous"),
        WebPartStorage(Storage.Shared),
        FriendlyName("ItemLimit"),
        Description("Query of the WebPart : the number of items to which the webpart is limited."),
        DefaultValue(100)]
        public uint ItemLimit
        {
            get { return _itemLimit; }
            set { _itemLimit = value; }
        }

        [Browsable(true), Category("Miscellaneous"),
        WebPartStorage(Storage.Shared),
        FriendlyName("DetailsPageUrl"),
        Description("Query of the WebPart : the URL of the page used to display the full content of the item."),
        DefaultValue("")]
        public string DetailsPageUrl
        {
            get { return _detailsPageUrl; }
            set { _detailsPageUrl = value; }
        }

        [Browsable(true), Category("Miscellaneous"),
        WebPartStorage(Storage.Shared),
        FriendlyName("NewFormPageUrl"),
        Description("Query of the WebPart : the URL of the page used to add a new item."),
        DefaultValue("")]
        public string NewFormPageUrl
        {
            get { return _newFormPageUrl; }
            set { _newFormPageUrl = value; }
        }

        [Browsable(true), Category("Miscellaneous"),
        WebPartStorage(Storage.Shared),
        FriendlyName("SortBy"),
        Description("Query of the WebPart : the column by which the item collection is sorted."),
        DefaultValue("Created")]
        public string SortBy
        {
            get { return _sortBy; }
            set { _sortBy = value; }
        }

        [Browsable(true), Category("Miscellaneous"),
        WebPartStorage(Storage.Shared),
        FriendlyName("SortOrder"),
        Description("Query of the WebPart : the order by which the item collection is sorted."),
        DefaultValue(false)]
        public bool SortOrder
        {
            get { return _sortOrder; }
            set { _sortOrder = value; }
        }

        [Browsable(true), Category("Miscellaneous"),
        WebPartStorage(Storage.Shared),
        FriendlyName("ItemLimitType"),
        Description("Query of the WebPart : the type of item limit."),
        DefaultValue(false)]
        public bool ItemLimitType
        {
            get { return _itemLimitType; }
            set { _itemLimitType = value; }
        }

        protected SPListItemCollection _currentUserListItems = null;

        #endregion

        #region Method overrides

        override public ToolPart[] GetToolParts()
        {
            ToolPart[] toolParts = new ToolPart[1];
            toolParts[0] = new WebPartToolPart();
            return toolParts;
        }

        static public string SetXslTransformer(string strXslUrl, XmlDocument xmlDoc)
        {
            try
            {
                StringWriter sw = new StringWriter();
                XslCompiledTransform xslTemplate = new XslCompiledTransform();
                WebRequest req = WebRequest.Create(strXslUrl);
                req.UseDefaultCredentials = true;
                WebResponse resp = req.GetResponse();
                XmlReader reader = XmlReader.Create(resp.GetResponseStream());
                xslTemplate.Load(reader);
                XsltArgumentList argsList = new XsltArgumentList();
                XSLUtilities obj = new XSLUtilities();
                argsList.AddExtensionObject("urn:Avanade", obj);
                xslTemplate.Transform(xmlDoc, argsList, sw);

                string returnstr = HttpUtility.HtmlDecode(sw.ToString());
                return returnstr;

            }
            catch (Exception e)
            {
                Log.Write(e.Message + "\r\n" + e.StackTrace, System.Diagnostics.EventLogEntryType.Error);
            }
            return string.Empty;
        }

        static public string SetXslTransformer(string strXslUrl, XDocument xDoc)
        {
            try
            {
                StringWriter sw = new StringWriter();
                XslCompiledTransform xslTemplate = new XslCompiledTransform();
                WebRequest req = WebRequest.Create(strXslUrl);
                req.UseDefaultCredentials = true;
                WebResponse resp = req.GetResponse();
                XmlReader reader = XmlReader.Create(resp.GetResponseStream());
                xslTemplate.Load(reader);
                XsltArgumentList argsList = new XsltArgumentList();
                XSLUtilities obj = new XSLUtilities();
                argsList.AddExtensionObject("urn:Avanade", obj);
                xslTemplate.Transform(xDoc.CreateReader(), argsList, sw);

                string returnstr = HttpUtility.HtmlDecode(sw.ToString());
                return returnstr;

            }
            catch (Exception e)
            {
                Log.Write(e.Message + "\r\n" + e.StackTrace, System.Diagnostics.EventLogEntryType.Error);
            }
            return string.Empty;
        }

        protected void WriteTraceXml(XmlDocument xmlDoc, string fileName)
        {
            try
            {
                string strPath = SPUtility.GetVersionedGenericSetupPath(@"TEMPLATE\LAYOUTS\XSLTemplates\Temp\", 15);
                //Environment.GetFolderPath(Environment.SpecialFolder.CommonProgramFiles)
                //+ @"\Microsoft Shared\Web Server Extensions\12\TEMPLATE\LAYOUTS\XSLTemplates\Temp\";

                string strPathXmlTemp = strPath + fileName + "_" + this.Title + @".xml";
                xmlDoc.Save(strPathXmlTemp);
            }
            catch (System.Exception) { }
        }

        protected StringBuilder sbTrace = new StringBuilder();
        protected DateTime dtCurrent = DateTime.Now;

        protected void AddTrace(string mess)
        {
            if (this.Context.User.Identity.Name.ToUpper().Contains("CLRSTRM-ADMMOSS"))
            {
                TimeSpan tsTimeLastTrace = DateTime.Now - dtCurrent;

                sbTrace.AppendLine(DateTime.Now.ToString("dd/MM/yyyy HH:mm:ss.fff")
                    + " " + tsTimeLastTrace.Seconds + "," + tsTimeLastTrace.Milliseconds.ToString("000")
                    + " " + mess);

                dtCurrent = DateTime.Now;
            }
        }

        public static string GetPathForXSL(string fileName)
        {
            string trombiPath = SPUtility.GetVersionedGenericSetupPath(@"TEMPLATE\LAYOUTS\VPLink2013\XSL\Trombinoscope", 15);
            return string.Format("{0}/_layouts/15/VPLink2013/XSL/Trombinoscope/{1}", SPContext.Current.Web.Url, fileName);
            //return "http://vplink/Documents XSL/" + fileName;
        }


        #endregion
    }
}
